<?php
declare(strict_types=1);

namespace app\service;

use app\model\User;
use think\facade\Cache;

class SidService
{
    /**
     * 生成sid
     * @param int $merchantId 商家ID
     * @param int $userId 用户ID
     * @return string
     */
    public function generateSid(int $merchantId, int $userId): string
    {
        // 格式: m{merchant_id}_u{user_id}_{timestamp}_{random}
        return sprintf(
            'm%d_u%d_%d_%s',
            $merchantId,
            $userId,
            time(),
            substr(md5(uniqid()), 0, 6)
        );
    }

    /**
     * 从sid中解析商家ID
     * @param string $sid sid字符串
     * @return int
     */
    public function getMerchantId(string $sid): int
    {
        if (preg_match('/^m(\d+)_u\d+_\d+_[a-f0-9]{6}$/', $sid, $matches)) {
            return (int)$matches[1];
        }
        return 0;
    }

    /**
     * 从sid中解析用户ID
     * @param string $sid sid字符串
     * @return int
     */
    public function getUserId(string $sid): int
    {
        if (preg_match('/^m\d+_u(\d+)_\d+_[a-f0-9]{6}$/', $sid, $matches)) {
            return (int)$matches[1];
        }
        return 0;
    }

    /**
     * 验证sid格式是否正确
     * @param string $sid sid字符串
     * @return bool
     */
    public function validateSid(string $sid): bool
    {
        return (bool)preg_match('/^m\d+_u\d+_\d+_[a-f0-9]{6}$/', $sid);
    }
} 